package com.shengde.jinwawaforleader.model.myJob.instance_message;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.shengde.jinwawaforleader.MyselfBroadCastReceiver;
import com.shengde.jinwawaforleader.R;
import com.shengde.jinwawaforleader.base.BaseActivity;
import com.shengde.jinwawaforleader.bean.User;
import com.shengde.jinwawaforleader.network.BaseProtocol;
import com.shengde.jinwawaforleader.network.protocolbean.ProLinkmenList;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;


/**
 * 即时通讯(家园沟通)
 * Created by Administrator on 2016/9/29 0029.
 */
public class InstanceMessageActivity extends BaseActivity {
	private static final int LOGIN_SUCCESS = 1;
	private static final String TAG = "InstanceMessageActivity";
	private static final int CONTACT = 2;
	private static final int CONTACT_OK = 3;
	private final static int MSG_REFRESH = 4;
	private static final int LOGIN_FAIL = 5;

	private TextView tv_back;
	private TextView tv_title;
	private TextView fill_add;
	protected List<EMConversation> conversationList = new ArrayList<EMConversation>();
	public static List<ProLinkmenList.DataBean> DataBean;  //服务器返回的bean
	MyselfBroadCastReceiver myselfBroadCastReceiver;

	protected EaseConversationList conversationListView;  //会话的列表
	private LinearLayout loading_main; //加载中
	private LinearLayout loading_no_recourse;  //暂未数据
	public Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case LOGIN_SUCCESS:
					// register context menu
					conversationList.addAll(loadConversationList());

					conversationListView.init(conversationList);
					conversationListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
						@Override
						public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
							final Dialog dialog = new Dialog(InstanceMessageActivity.this, R.style.dialog);
							View contentView = LayoutInflater.from(InstanceMessageActivity.this).inflate(
									R.layout.dialog_exit, null);
							dialog.setContentView(contentView);
							dialog.setCanceledOnTouchOutside(true);
							dialog.show();
							TextView textView1990 = (TextView) contentView.findViewById(R.id.textView1990);
							textView1990.setText("确定删除当前会话吗?");
							TextView ok = (TextView) contentView.findViewById(R.id.button_ok);
							TextView cacel = (TextView) contentView.findViewById(R.id.button_cacel);
							ok.setOnClickListener(new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									dialog.dismiss();
									//删除和某个user会话，如果需要保留聊天记录，传false
									EMClient.getInstance().chatManager().deleteConversation(conversationList.get(position).getUserName(), true);
									mHandler.sendEmptyMessage(MSG_REFRESH);

								}
							});
							cacel.setOnClickListener(new View.OnClickListener() {
								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							});
							return true;
						}
					});
					registerForContextMenu(conversationListView);
					conversationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
							EMConversation conversation = conversationListView.getItem(position);
							String username = conversation.getUserName();
							EMConversation conversations = EMClient.getInstance().chatManager().getConversation(username);
							//指定会话消息未读数清零
							conversations.markAllMessagesAsRead();
							if (username.equals(EMClient.getInstance().getCurrentUser()))
								Toast.makeText(InstanceMessageActivity.this, R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
							else {
								// start chat acitivity
								Intent intent = new Intent(InstanceMessageActivity.this, ChatActivity.class);
								if (conversation.isGroup()) {
									if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
										// it's group chat
										intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_CHATROOM);
									} else {
										intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
									}
								}
								// it's single chat
								String mUserName = null;
								String mLogo = null;
								for(int i = 0; i < DataBean.size(); i++) {
									for(int j = 0; j < DataBean.get(i).getData().size(); j++) {
										if(!TextUtils.isEmpty(username)&&username.equals(DataBean.get(i).getData().get(j).getTel())) {
											mLogo=DataBean.get(i).getData().get(j).getLogo();
											mUserName =DataBean.get(i).getData().get(j).getName();
										}
									}
								}
								Log.i(TAG, "onItemClick: mUserName"+mUserName);
								Log.i(TAG, "onItemClick: username"+username);
								Log.i(TAG, "onItemClick: mLogo"+mLogo);
								Log.i(TAG, "onItemClick: mylogo"+ User.getUserPhoto(InstanceMessageActivity.this));
								intent.putExtra(Constant.EXTRA_USER_Name, mUserName);
								intent.putExtra(Constant.EXTRA_USER_ID, username);
								intent.putExtra(Constant.EXTRA_USER_Logo, mLogo);
								intent.putExtra(Constant.EXTRA_USER_Logo_Myself, User.getUserPhoto(InstanceMessageActivity.this));
								startActivity(intent);
							}
						}
					});
					break;
				case MSG_REFRESH: {

					conversationList.clear();
					conversationList.addAll(loadConversationList());
					conversationListView.refresh();
					break;
				}
				case LOGIN_FAIL:
					loading_no_recourse.setVisibility(View.INVISIBLE);
			}
		}
	};


	@Override
	public void onRoot(Bundle savedInstanceState) {
		setContentView(R.layout.instance_message_activity);

	}

	@Override
	public void initView() {
		tv_back = (TextView) findViewById(R.id.tv_back);
		tv_title = (TextView) findViewById(R.id.tv_title);
		fill_add = (TextView) findViewById(R.id.fill_add);
		conversationListView = (EaseConversationList) findViewById(R.id.list);

		loading_main = (LinearLayout) findViewById(R.id.loading_main);
		loading_no_recourse = (LinearLayout) findViewById(R.id.loading_no_recourse);
	}

	@Override
	public void initData() {
		fill_add.setText(getString(R.string.linkmanActivity));
		tv_title.setText(getString(R.string.instance_message));
//		DemoDBManager.getInstance().closeDB();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constant.REFRESH);
		//注册
		myselfBroadCastReceiver = new MyselfBroadCastReceiver(){
			@Override
			public void onReceive(Context context, Intent intent) {
				super.onReceive(context, intent);
				if (intent.getAction()==Constant.REFRESH){
					mHandler.sendEmptyMessage(MSG_REFRESH);
				}
			}
		};

		registerReceiver(myselfBroadCastReceiver, intentFilter);
		showLinkmenList();

	}

	@Override
	public void initListener() {
		tv_back.setOnClickListener(this);
		fill_add.setOnClickListener(this);
	}

	@Override
	public void onWidgetClick(View view) {
		switch (view.getId()) {
			case R.id.tv_back:
				finish();
				break;
			case R.id.fill_add:
				getIntentCallBack().startActivityForResultCommon(LinkManActivity.class, CONTACT);
				break;
		}
	}

	protected List<EMConversation> loadConversationList() {
		// get all conversations
		Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
		Log.i(TAG, "handleMessage: conversations33333333" + conversations.size());

		if (conversations.size() == 0) {
			loading_main.setVisibility(View.GONE);
			loading_no_recourse.setVisibility(View.VISIBLE);
		} else {
			loading_main.setVisibility(View.GONE);
			loading_no_recourse.setVisibility(View.GONE);
		}
		List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
		/**
		 * lastMsgTime will change if there is new message during sorting
		 * so use synchronized to make sure timestamp of last message won't change.
		 */
		synchronized (conversations) {
			for (EMConversation conversation : conversations.values()) {
				if (conversation.getAllMessages().size() != 0) {
					sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
				}
			}
		}
		try {
			// Internal is TimSort algorithm, has bug
			sortConversationByLastChatTime(sortList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<EMConversation> list = new ArrayList<EMConversation>();
		for (Pair<Long, EMConversation> sortItem : sortList) {
			list.add(sortItem.second);
		}
		return list;
	}

	/**
	 * sort conversations according time stamp of last message
	 *
	 * @param conversationList
	 */
	private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
		Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
			@Override
			public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

				if (con1.first.equals(con2.first)) {
					return 0;
				} else if (con2.first.longValue() > con1.first.longValue()) {
					return 1;
				} else {
					return -1;
				}
			}

		});
	}

	/**
	 * 获取联系人列表(通过自己服务端获取)
	 */
	private void showLinkmenList() {
		String url = "";
		if (User.isTest) {
			url = BaseProtocol.HOST_BASE_TEST + "/director/friends";
		} else {
			url = BaseProtocol.HOST_BASE + "/director/friends";
		}
		RequestParams params  = BaseProtocol.getRequestParams(url);
		params.addParameter("schoolid", User.getSchoolId(this));
		params.addParameter("userid", User.getUserLoginAccount(this));
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				ProLinkmenList pro_class_status = new Gson().fromJson(result, ProLinkmenList.class);
				if (pro_class_status != null && pro_class_status.getCode() == 0) {
					DataBean = pro_class_status.getData();
					mHandler.sendEmptyMessage(LOGIN_SUCCESS);
				}

			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {

			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {

			}
		});
	}
}
